package com.taotao.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.rpc.Result;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.common.util.JsonUtils;
import com.taotao.sso.service.UserLoginService;

@Controller
public class UserLoginController {
	
	@Autowired
	private UserLoginService userService;
	
	@Value("${TT_TOKEN_KEY}")
	private String TT_TOKEN_KEY;

	/**
	 * url : /user/login
	 * param : username//用户名
	 * param : password//密码
	 */
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult login(HttpServletRequest request,HttpServletResponse response,String username,String password) {
		//1.引入服务
		//2.注入服务
		//3.调用方法
		//4.需要设置token到cookie中，使用工具类cookie跨域
		TaotaoResult result = userService.login(username, password);
		if(result.getStatus() == 200) {
			CookieUtils.setCookie(request, response, TT_TOKEN_KEY, result.getData().toString());
		}
		return result;
	}
	
	/**
	 * url: /user/token/{token}
	 * param : token 令牌
	 */
	@RequestMapping(value="/user/token/{token}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String getUserByToken(@PathVariable String token,String callback) {
		//判断是否jsonp请求
		if(StringUtils.isNotBlank(callback)) {
			//如果是jsonp 需要拼接 类似于fun(id:1)
			TaotaoResult result = userService.getUserBytoken(token);
			String jsonpStr= callback + "(" + JsonUtils.objectToJson(result) + ")" ;
			return jsonpStr;
		}
		
		//调用服务
		TaotaoResult result = userService.getUserBytoken(token);
		return JsonUtils.objectToJson(result);
	}
	
	/**
	 * url : /user/logout
	 * param : username//用户名
	 * param : password//密码
	 */
	@RequestMapping(value="/user/logout/{token}",method=RequestMethod.GET)
	public String logout(HttpServletRequest request,HttpServletResponse response,@PathVariable String token,String callback) {
		//1.引入服务
		//2.注入服务
		//3.调用方法
		userService.logoutAndDeleteToken(token);
		//4.需要删除cookie中的token
		CookieUtils.deleteCookie(request, response, TT_TOKEN_KEY);

		return "redirect:/page/login";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
